package top.jlzhou.qqnews;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.geccocrawler.gecco.pipeline.Pipeline;
import com.geccocrawler.gecco.pipeline.PipelineFactory;
import com.geccocrawler.gecco.spider.SpiderBean;

@Service
public class SpringPipelineFactory implements PipelineFactory, ApplicationContextAware {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private ApplicationContext applicationContext;
	
	@Resource(name="defaultPipeline")
	private Pipeline<? extends SpiderBean> defaultPipeline;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	
	public void setDefaultPipeline(Pipeline<? extends SpiderBean> defaultPipeline) {
		this.defaultPipeline = defaultPipeline;
	}


	@Override
	public Pipeline<? extends SpiderBean> getPipeline(String name) {
		logger.debug("获取Pipeline："+name);
		try {
			Object bean = applicationContext.getBean(name);
			if (bean instanceof Pipeline) {
				return (Pipeline<? extends SpiderBean>) bean;
			}
		} catch (NoSuchBeanDefinitionException ex) {
			logger.warn("获取Pipeline失败："+name, ex);
		}
		return defaultPipeline;
	}

}
